<template>
    <el-date-picker
        v-model="value"
        type="month"
        :disabled="disabled"
        value-format="yyyy.MM"
        @change="onDateChange"
        placeholder="选择年月">
    </el-date-picker>
</template>

<script>
export default {
	name: 'NameIdSelect',
    model: {
        props: 'value',
        event: 'change',
    },
    props: {
        value: {
            type: [Number, String],
        },
        required: {
            type: Boolean,
            default: true,
        }
    },
    data(){
        return {
            disabled: true,
        }
    },
    watch: {
        required: {
            handler(val){
                if(val){
                    this.disabled = !this.value;
                }else{
                    this.disabled = false;
                }
            },
            immediate: true,
        }
    },
	created() {
        if(this.value){
            this.disabled = false;
            this.onDateChange(this.value);
        }else if(this.required){
            // 如果是一定要有数据，则需要请求
            this.$axios.get('/admin/boat/data/reportDateList').then((res) => {
                const {result = [], success} = res;
                if(success){
                    // 获得数据后，现在可以使用了
                    this.disabled = false;
                    // 要找到第一个是 YYYY.MM 格式的
                    const reg = /^\d{4}\.\d{2}$/;
                    const date = result.find((item) => {
                        return reg.test(item.report_date);
                    });
                    if(date){
                        this.onDateChange(date.report_date);
                    }
                }
            }).catch(e => {
                console.log(e);
            });
        }
        
	},
    methods: {
        onDateChange(e){
            this.$emit('change', e);
        },
    }
};
</script>